<template>
  <div>
    <div v-clickoutside="hideReplyBtn" class="my-reply" @click="inputFocus">
      <el-avatar class="header-img" :size="40" :src="user_avatar" />
      <div class="reply-info">
        <div
          id="replyInput"
          tabindex="0"
          contenteditable="true"
          spellcheck="false"
          placeholder="输入评论..."
          class="reply-input"
          @focus="showReplyBtn"
          @input="onDivInput($event)"
        />
      </div>
      <div v-show="btnShow" class="reply-btn-box">
        <el-button
          class="reply-btn"
          size="medium"
          type="primary"
          @click="sendComment"
        >
          发表评论
        </el-button>
      </div>
    </div>
    <div
      v-for="(item, i) in comments"
      :key="i"
      class="author-title reply-father"
    >
      <el-avatar class="header-img" :size="40" :src="item.avatar" />
      <div class="author-info">
        <span class="author-name">{{ item.username }}</span>
        <span class="author-time">{{ item.createTime }}</span>
      </div>
      <div class="icon-btn">
        <span @click="showReplyInput(i, '0', item.id, item.id, null)">
          <i class="iconfont icon-pinglun" />
          {{ item.commentNum }}
        </span>
        <!-- <span  @click="addlikeNumber(i, item.from, item.id)">
        <i class="iconfont el-icon-caret-top"></i>
        {{ item.like }}
        </span> -->
        <span class="xin" @click="countlikeNumber('1',i,0,item.id)">
          <i v-if="item.isLike" class="iconfont icon-dianzan_kuai">&#xe607;</i>
          <i v-else class="iconfont icon-dianzan">&#xe68b;</i>
          {{ item.like }}
        </span>
      </div>
      <div class="talk-box">
        <p>
          <span class="reply">{{ item.content }}</span>
          <span class="report" @click="addCommentReport(item.id)">举报</span>
        </p>
      </div>
      <div class="reply-box">
        <div v-for="(reply, j) in item.reply" :key="j" class="author-title">
          <el-avatar
            class="header-img"
            :size="40"
            :src="reply.avatar"
          />
          <div class="author-info">
            <span class="author-name">{{ reply.username }}</span>
            <span class="author-time">{{ reply.createTime }}</span>
          </div>
          <div class="icon-btn">
            <span @click="showReplyInput(i, j, reply.id, reply.rootCommentId, reply.username)">
              <i class="iconfont icon-pinglun" />
              {{ reply.commentNum }}
            </span>
            <span @click="countlikeNumber('2',i,j,reply.id)">
              <i v-if="reply.isLike" class="iconfont icon-dianzan_kuai" />
              <i v-else class="iconfont icon-dianzan" />
              {{ reply.like }}
            </span>
          </div>
          <div class="talk-box">
            <p>
              <span>回复 {{ reply._username }}:</span>
              <span class="reply">{{ reply.content }}</span>
              <span class="report" @click="addCommentReport(reply.id)">举报</span>
            </p>
          </div>
          <div class="reply-box" />
        </div>
      </div>
      <div v-show="_inputShow(i)" class="my-reply my-comment-reply">
        <el-avatar class="header-img" :size="40" :src="user_avatar" />
        <div class="reply-info">
          <div
            tabindex="0"
            contenteditable="true"
            spellcheck="false"
            placeholder="输入评论..."
            class="reply-input reply-comment-input"
            autofocus
            @input="onDivInput($event)"
          />
        </div>
        <div class="reply-btn-box">
          <el-button
            class="reply-btn"
            size="medium"
            type="primary"
            @click="sendCommentReply(i)"
          >
            发表回复
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e)
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.vueClickOutside = documentHandler
    document.addEventListener('click', documentHandler)
  },
  update() {},
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener('click', el.vueClickOutside)
    delete el.vueClickOutside
  }
}
import { addComment, findComments, like, disLike } from '@/api/comment'
import { addReport } from '@/api/report'
import Swal from 'sweetalert2'
export default {
  name: 'ArticleComment',
  directives: { clickoutside },
  data() {
    return {
      btnShow: false,
      index: '0',
      replyComment: '',
      subIndex: '0',
      to_username: '',
      toId: -1,
      parentCommentId: '',
      rootCommentId: '',
      comments: [
        {
          username: 'Lana Del Rey',
          id: '',
          userId: '',
          avatar: '',
          content: '我发布一张新专辑Norman Fucking Rockwell,大家快来听啊',
          createTime: '2019年9月16日 18:43',
          inputShow: false,
          commentNum: 1,
          like: 15,
          isLike: false,
          likeListId: [],
          reply: [
            {
              username: 'Taylor Swift',
              id: '',
              avatar:
                  'https://ae01.alicdn.com/kf/H94c78935ffa64e7e977544d19ecebf06L.jpg',
              parentCommentUsername: 'Lana Del Rey',
              rootCommentId: '',
              parentCommentId: 19870621,
              _username: '',
              content: '我很喜欢你的新专辑！！',
              createTime: '2019年9月16日 18:43',
              commentNum: 1,
              like: 15,
              isLike: false,
              likeListId: [],
              inputShow: false
            },
            {
              from: 'Ariana Grande',
              fromId: 1123,
              fromHeadImg:
                  'https://ae01.alicdn.com/kf/Hf6c0b4a7428b4edf866a9fbab75568e6U.jpg',
              to: 'Lana Del Rey',
              toId: 19870621,
              comment: '别忘记宣传我们的合作单曲啊',
              time: '2019年9月16日 18:43',
              commentNum: 0,
              like: 5,
              isLike: false,
              likeListId: [],
              inputShow: false
            }
          ]
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'user_username',
      'user_avatar',
      'user_id'
    ])
  },
  mounted() {
    this.findComments()
    console.log(this.$store.state.user.id)
  },
  methods: {
    inputFocus() {
      var replyInput = document.getElementById('replyInput')
      replyInput.style.padding = '8px 8px'
      replyInput.style.border = '2px solid blue'
      replyInput.focus()
    },
    showReplyBtn() {
      this.btnShow = true
    },
    hideReplyBtn() {
      this.btnShow = false
      var replyInput = document.getElementById('replyInput')
      replyInput.style.padding = '10px'
      replyInput.style.border = 'none'
    },
    showReplyInput(i, j, parentCommentId, rootCommentId, username) {
      this.comments[this.index].inputShow = false
      this.index = i
      this.comments[i].inputShow = true
      this.toId = i
      this.subIndex = j === '0' ? '0' : j
      this.to_username = username
      this.parentCommentId = parentCommentId
      this.rootCommentId = rootCommentId
    },
    // addlikeNumber(i, id) {
    //   console.log(this.comments[i])
    //   const list = this.comments[i].likeListId
    //   // console.log(i, name, id)
    //   if (list.length === 0) {
    //     // 在已经点赞的列表中未找到userId
    //     this.comments[i].isLike = true
    //     this.comments[i].like += 1
    //     this.comments[i].likeListId.push(id)
    //     console.log('点赞+1', this.comments[i].isLike, this.comments[i].like, this.comments[i].likeListId)
    //   } else {
    //     const index = list.indexOf(this.user_id)
    //     this.comments[i].isLike = false
    //     this.comments[i].like -= 1
    //     this.comments[i].likeListId.splice(index, 1)
    //     console.log('点赞-1', this.comments[i].isLike, this.comments[i].likeListId)
    //   }
    // },
    countlikeNumber(type, i, j, id) {
      const text = type === '1' ? this.comments[i] : this.comments[i].reply[j]
      const list = text.likeListId

      if (!list.includes(this.$store.state.user.id)) {
        // 在已经点赞的列表中未找到userId
        text.isLike = true
        text.like += 1
        text.likeListId.push(this.$store.state.user.id)
        console.log(text.likeListId)
        like({ userId: this.$store.state.user.id, articleId: this.$route.params.id, commentId: id }).then(res => {
        })
        console.log('点赞+1', text.isLike, text.like, text.likeListId)
      } else {
        const index = list.indexOf(this.$store.state.user.id)
        text.isLike = false
        text.like -= 1
        text.likeListId.splice(index, 1)
        console.log(text.likeListId)
        disLike({ userId: this.$store.state.user.id, articleId: this.$route.params.id, commentId: id }).then(res => {

        })
        console.log('点赞-1', text.isLike, text.likeListId)
      }
    },
    _inputShow(i) {
      return this.comments[i].inputShow
    },
    findComments() {
      findComments({ articleId: this.$route.params.id, userId: this.$store.state.user.id }).then(res => {
        this.comments = res.data
        console.log(res.data)
      })
    },
    sendComment() {
      if (this.$store.state.user.id === '') {
        this.$message({
          type: 'info',
          message: '请先登录'
        })
        return
      }
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '评论不能为空'
        })
      } else {
        const a = {}
        const input = document.getElementById('replyInput')
        const timeNow = new Date().getTime()
        const time = this.dateStr(timeNow)
        a.username = this.user_username
        a.content = this.replyComment
        a.avatar = this.user_avatar
        a.createTime = time
        a.commentNum = 0
        a.like = 0
        a.userId = this.user_id
        a.reply = []
        a.isLike = false
        a.likeListId = []
        addComment({ articleId: this.$route.params.id, content: this.replyComment,
          userId: this.$store.state.user.id }).then(res => {
          a.id = res.data.id
          a.rootCommentId = res.data.rootCommentId
        })
        this.comments.unshift(a)
        this.replyComment = ''
        input.innerHTML = ''
      }
    },
    sendCommentReply(i) {
      if (this.$store.state.user.id === '') {
        this.$message({
          type: 'info',
          message: '请先登录'
        })
        return
      }
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: 'warning',
          message: '回复不能为空'
        })
      } else {
        const a = {}
        const timeNow = new Date().getTime()
        const time = this.dateStr(timeNow)
        a.username = this.user_username
        a._username = this.to_username
        a.avatar = this.user_avatar
        a.content = this.replyComment
        a.createTime = time
        a.commentNum = 0
        a.like = 0
        a.isLike = false
        a.likeListId = []
        this.comments[i].reply.push(a)
        addComment({ articleId: this.$route.params.id, userId: this.$store.state.user.id,
          content: this.replyComment, parentCommentId: this.parentCommentId, rootCommentId: this.rootCommentId }).then(res => {
          a.id = res.data.id
          a.rootCommentId = res.data.rootCommentId
        })
        this.replyComment = ''
        this.parentCommentId = ''
        this.rootCommentId = ''
        document.getElementsByClassName('reply-comment-input')[i].innerHTML =
            ''
      }
    },
    onDivInput: function(e) {
      this.replyComment = e.target.innerHTML
    },
    dateStr(date) {
      // 获取js 时间戳
      var time = new Date().getTime()
      // 去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000)
      // 存储转换值
      var s
      if (time < 60 * 10) {
        // 十分钟内
        return '刚刚'
      } else if (time < 60 * 60 && time >= 60 * 10) {
        // 超过十分钟少于1小时
        s = Math.floor(time / 60)
        return s + '分钟前'
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        // 超过1小时少于24小时
        s = Math.floor(time / 60 / 60)
        return s + '小时前'
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        // 超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24)
        return s + '天前'
      } else {
        // 超过30天ddd
        var date_ = new Date(parseInt(date))
        return (
          date_.getFullYear() +
            '/' +
            (date_.getMonth() + 1) +
            '/' +
            date_.getDate()
        )
      }
    },
    addCommentReport(id) {
      Swal.fire({
        title: '确定要举报吗?',
        icon: 'question',
        confirmButtonText: '确定',
        showCancelButton: true,
        cancelButtonText: '取消',
        heightAuto: false
      }).then(res => {
        if (res.isConfirmed) {
          addReport({ userId: this.$store.getters.user_id, itemId: this.$route.params.id,
            reportType: 0 }).then(res => {
            if (res.code === 1) {
              Swal.fire('举报成功!', '', 'success')
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .my-reply {
    padding: 10px;
    background-color: #fafbfc;
    .header-img {
      display: inline-block;
      vertical-align: top;
    }
    .reply-info {
      display: inline-block;
      margin-left: 5px;
      width: 90%;
      //根据屏幕宽度自适应
      @media screen and(max-width:1200px) {
        width: 80%;
      }
      .reply-input {
        min-height: 20px;
        line-height: 22px;
        padding: 10px 10px;
        color: #ccc;
        background-color: #fff;
        border-radius: 5px;
          // &:empty::before{
          //   content attr(placeholder);
          // }
        &:empty:before {
          content: attr(placeholder);
        }
        &:focus:before {
          content: none;
        }
        &:focus {
          padding: 8px 8px;
          border: 2px solid blue;
          box-shadow: none;
          outline: none;
          }
      }
    }
    .reply-btn-box {
      height: 25px;
      // margin: 10px 0;
      display: inline-block;
      .reply-btn {
        position: relative;
        float: right;
        margin-left: 15px;
        // margin-right: 15px;
        }
      }
  }
  .my-comment-reply {
    margin-left: 50px;
    .reply-input {
      width: flex;
    }
  }
  .author-title:not(:last-child) {
    border-bottom: 1px solid rgba(74, 136, 199, .3)
  }
  .reply-father {
    padding: 10px;
    .header-img {
      display: inline-block;
      vertical-align: top;
    }
    .author-info {
      display: inline-block;
      margin-left: 5px;
      width: 60%;
      height: 40px;
      line-height: 20px;
      span {
        display: block;
        cursor: pointer;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .author-name {
        color: #000;
        font-size: 18px;
        font-weight: bold;
      }
      .author-time {
        font-size: 14px;
      }
    }
    .icon-btn {
      width: 30%;
      padding: 0 !important ;
      float: right;
      @media screen and (max-width: 1200px) {
        width: 20%;
        padding: 7px;
      }
      span {
        cursor: pointer;
      }
      .iconfont {
        margin: 0 5px;
      }
    }
    .talk-box {
      margin: 0 50px;
      p {
        margin: 0;
      }
      .reply {
        font-size: 16px;
        color: #000;
      }
    }
    .reply-box {
      margin: 10px 0 0 50px;
      background-color: #efefef;
    }
  }
  .report {
    font-size: 14px;
    color: #9999b3;
    margin-left: 50px;
    cursor: pointer;
  }
</style>
